﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System.Runtime.InteropServices;

namespace BitwiseOre.SharedMemory.Core.Primatives
{
    internal class SharedArray<T> : IArray<T> where T : struct
    {
        private readonly IUnmanagedMemoryAccessor _accessor;
        private static readonly int SizeOfT = Marshal.SizeOf(typeof(T));

        public SharedArray(IUnmanagedMemoryAccessor accessor)
        {
            _accessor = accessor;
        }

        public T this[int index]
        {
            get
            {
                T value;
                _accessor.Read(GetOffset(index), out value);
                return value;
            }
            set
            {
                _accessor.Write(GetOffset(index), ref value);
            }
        }

        public int Capacity
        {
            get { return (int)_accessor.Capacity; }
        }

        public int Count
        {
            get { return Capacity/SizeOfT; }
        }

        protected static int GetOffset(int index)
        {
            return index*SizeOfT;
        }

        protected IUnmanagedMemoryAccessor Accessor
        {
            get { return _accessor; }
        }
    }
}